package com.mecol.education.controller;

import com.mecol.education.entity.Admin;
import com.mecol.education.entity.AdminUserRole;
import com.mecol.education.result.Result;
import com.mecol.education.result.ResultFactory;
import com.mecol.education.service.AdminService;
import com.mecol.education.service.AdminUserRoleService;
import com.mecol.education.util.StringUtils;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private AdminUserRoleService adminUserRoleService;
    @GetMapping("/api/admin/user")
    public Result lsitUsers(){
        return ResultFactory.buildSuccessResult(adminService.list());
    }
    @PutMapping("/api/admin/user/status")
    public Result updateUserStatus(@RequestBody Admin admin){
        adminService.updateUserStatus(admin);
        return ResultFactory.buildSuccessResult("用户状态更新成功");
    }
    @PutMapping("/api/admin/user/password")
    public Result resetPassword(@RequestBody Admin admin){
        adminService.resetPassword(admin);
        return ResultFactory.buildSuccessResult("重置密码成功");
    }
    @PutMapping("/api/admin/removeUser")
    public Result removeUser(@RequestBody Admin admin){
        adminUserRoleService.remove(admin.getId()); //还要把AdminUserRole中的 这个user对应的删除

        adminService.removeUser(admin);
         return ResultFactory.buildSuccessResult("移除成功");
    }
    @PutMapping("/api/admin/user")
    public Result editUser(@RequestBody Admin admin){

        adminService.editUser(admin);
        return ResultFactory.buildSuccessResult("修改成功");
    }

    @PostMapping("/api/admin/img")
    public String coversUpload(MultipartFile file) {
        String folder = "D:/education/img";
        File imageFolder = new File(folder);
        File f = new File(imageFolder,
                StringUtils.getRandomString(6)
                        + file.getOriginalFilename()
                        .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8443/api/file/"
                    + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }



}
